import 'package:flutter/material.dart';

class HexColor extends Color {
  static _getColorFromHex(dynamic hexColor) {
    if (hexColor is Color) {
      return hexColor.value;
    } else if (hexColor is String) {
      if (hexColor.isNotEmpty && hexColor.indexOf('rgba') != -1) {
        return getRGBA(hexColor);
      } else if (hexColor.isNotEmpty && hexColor.indexOf('rgb') != -1) {
        return getRGB(hexColor);
      } else if (hexColor.isNotEmpty && hexColor.indexOf('#') != -1) {
        hexColor = hexColor.toUpperCase().replaceAll("#", "");
        hexColor = hexColor.replaceAll('0X', '');
        if (hexColor.length == 6) {
          hexColor = "FF" + hexColor;
        }
        return int.parse(hexColor, radix: 16);
      } else if (hexColor.isNotEmpty) {
        Map<String, Color> colorObj = {
          'black': Colors.black,
          'red': HexColor("rgba(255,0,0,1)"),
          'white': Colors.white,
          'blue': HexColor("rgba(0,0,255,1)"),
          'yellow': HexColor("rgba(255,255,0,1)"),
          'green': HexColor("rgba(0,255,0,1)"),
        };
        return colorObj[hexColor]?.value ?? 0;
      }
    }
    return 0;
  }

  static LinearGradient getLineGradient(String color) {
    final String str = color.replaceAll('linear-gradient(', '');
    final String splitText = str.substring(0, str.length - 1);
    final List<String> strList = splitText.split(RegExp(r',(?![^()]*\))'));
    List<String> colorArr;
    if (strList[0].indexOf('top') != -1 ||
        strList[0].indexOf('left') != -1 ||
        strList[0].indexOf('right') != -1 ||
        strList[0].indexOf('bottom') != -1) {
      colorArr = strList.sublist(1);
    } else {
      colorArr = strList;
    }
    return LinearGradient(colors: colorArr.map((e) => HexColor(e)).toList());
  }

  static int getRGB(String c) {
    String str = c.replaceAll('rgb(', '').replaceAll(')', '');
    List<String> split = str.split(',');
    double r = double.parse(split[0]);
    double g = double.parse(split[1]);
    double b = double.parse(split[2]);
    return getArgb(1.0, r.toInt(), g.toInt(), b.toInt());
  }

  static int getRGBA(String c) {
    String str = c.replaceAll('rgba(', '').replaceAll(')', '');
    List<String> split = str.split(',');
    double r = double.parse(split[0]);
    double g = double.parse(split[1]);
    double b = double.parse(split[2]);
    double a = double.parse(split[3]);
    return getArgb(a, r.toInt(), g.toInt(), b.toInt());
  }

  static int getArgb(double a, int r, int g, int b) {
    return Color.fromRGBO(r, g, b, a).value;
  }

  HexColor(final dynamic hexColor) : super(_getColorFromHex(hexColor));
}
